// Internal action code for project skygarden

package math;
import java.util.ArrayList;
import java.util.List;

import env.GardenModel;

import jason.asSemantics.*;
import jason.asSyntax.*;
import jason.environment.grid.Location;

@SuppressWarnings("serial")
public class closest_vegetable extends DefaultInternalAction {

	GardenModel model = GardenModel.get();
	List<Location> set = new ArrayList<Location>();
    @Override
    public Object execute(TransitionSystem ts, Unifier un, Term[] args) throws Exception {
       
    	int fromx = (int)((NumberTerm)args[0]).solve();
        int fromy = (int)((NumberTerm)args[1]).solve();
        int type = (int)((NumberTerm)args[2]).solve();
        
        Location from = new Location(fromx,fromy);
        
        if(AddLocation(type)) {
        	Location found = FindMinDistance(from);
        	un.unifies(args[3], new NumberTermImpl(found.x));
        	un.unifies(args[4], new NumberTermImpl(found.y));
        	set = new ArrayList<Location>();
        	return true;
        }
    	return false;
    }
    
    public boolean AddLocation(int type) {
    	for (int i = 0; i < model.Array().length; i++) {
			for (int j = 0; j < model.Array().length; j++) {
				if(model.Array()[i][j] == type) {
					set.add(new Location(i+5,j+5));
				}
			}
		}
    	return (set.size() != 0);
    }
    
    private Location FindMinDistance(Location pos) {
    	Location l = set.get(0);
    	int min = l.distance(pos);
    	for (Location _p : set) {
			if(_p.distance(pos) < min) {
				min = _p.distance(pos);
				l = _p;
			}
		}
    	return l;
    }
}
